﻿using System;
using Microsoft.VisualBasic.ApplicationServices;

namespace WickedFlame.VecDraw
{
    /// <summary>
    /// This class provides a workaround so that the application can be used as a single instance application.
    /// This class detects weather the application is already running or not. 
    /// It starts the application or gets the running instance and passes the arguments to the wpf application.
    /// 
    /// http://msdn.microsoft.com/en-us/library/ms771662.aspx
    /// </summary>
    public sealed class InstanceManager : WindowsFormsApplicationBase
    {
        [STAThread]
        public static void Main(string[] args)
        { 
            (new InstanceManager()).Run(args); 
        }

        public InstanceManager()
        { 
            IsSingleInstance = true; 
        }

        public VecDrawApplication App 
        { 
            get; 
            private set; 
        }

        protected override bool OnStartup(StartupEventArgs e)
        {
            App = new VecDrawApplication();
            App.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            base.OnStartupNextInstance(eventArgs);
            App.gui.Activate();

            string[] args = new string[eventArgs.CommandLine.Count];
            for (int i = 0; i < eventArgs.CommandLine.Count; i++)
                args[i] = eventArgs.CommandLine[i];

            App.ProcessArgs(args, false);
        }

        protected override bool OnUnhandledException(Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs e)
        {
            var sb = new System.Text.StringBuilder();
            sb.AppendLine("Error:");
            sb.AppendLine(e.Exception.Message);
            sb.AppendLine("StackTrace");
            sb.AppendLine(e.Exception.StackTrace);
            System.Windows.MessageBox.Show(sb.ToString());

            return base.OnUnhandledException(e);
        }
    }
}
